package mail;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import mail.bean.AccountBean;
import mail.bean.EmailUser;
import mail.bean.MessageVo;
import mail.impl.TextFileProcessor;

public class MailEditor extends JFrame {

	public final static int WIDTH = 640;

	public final static int HEIGHT = 480;

	private File toFile = null;
	private ArrayList<EmailUser> userList = null;
	private String contentType = "test/plain";

	// recipient information
	private JLabel toLabel = new JLabel("To: ");

	private JTextField toText = new JTextField();

	private JButton selFileBtn = new JButton("...");

	// subject information
	private JLabel subjectLabel = new JLabel("Subject: ");

	private JTextField subjectText = new JTextField();

	// sender information
	private JLabel senderLabel = new JLabel("Sender: ");

	private JTextField senderText = new JTextField();
	
	//send button
	private JButton sendBtn = null;

	// mail message information
	private JTabbedPane msgTab = null;

	private JEditorPane msgPreview = null;

	private JScrollPane previewScroll = null;

	private JEditorPane msgEdit = null;

	private JScrollPane editScroll = null;

	private JButton loadBtn = null;
	
	private AccountBean acct = null;
	
	JFileChooser chooser = null;

	public MailEditor(AccountBean acct) {
	  super();
	  this.acct = acct;
		init();
	}
	
	private void init() {
	  this.setSize(WIDTH, HEIGHT);
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    JPanel panel = new JPanel(null);

    // setup recipient information
    toText.setEditable(false);
    selFileBtn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        importUserFile();
      }
    });
    panel.add(toLabel);
    toLabel.setBounds(20, 10, 50, 20);
    panel.add(toText);
    toText.setBounds(80, 10, 450, 20);
    panel.add(selFileBtn);
    selFileBtn.setBounds(540, 10, 30, 20);

    // setup subject information
    panel.add(subjectLabel);
    subjectLabel.setBounds(20, 40, 50, 20);
    panel.add(subjectText);
    subjectText.setBounds(80, 40, 450, 20);
    
    //setup send button
    sendBtn = new JButton("Send");
    sendBtn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        sendEmail();
      }
    });
    panel.add(sendBtn);
    sendBtn.setBounds(20, 70, 80, 20);

    // setup sender information
    panel.add(senderLabel);
    senderLabel.setBounds(220, 70, 50, 20);
    panel.add(senderText);
    senderText.setText(acct.getAccountAddress());
    senderText.setBounds(280, 70, 250, 20);

    // setup message editor
    loadBtn = new JButton("Load Document");
    loadBtn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        loadDocument();
      }
    });
    panel.add(loadBtn);
    loadBtn.setBounds(110, 70, 100, 20);
    msgPreview = new JEditorPane("text/html", "");
    msgPreview.setEditable(false);
    previewScroll = new JScrollPane(msgPreview);
    msgEdit = new JEditorPane();
    msgEdit.setText("");
    editScroll = new JScrollPane(msgEdit);
    msgTab = new JTabbedPane(2);
    msgTab.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        tabChange();
      }
    });
    msgTab.addTab("Edit", editScroll);
    

    panel.add(msgTab);
    msgTab.setBounds(20, 100, 550, 330);

    this.setContentPane(panel);
    
    chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Email document", "html", "htm", "rtf");
    chooser.setFileFilter(filter);
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.setCurrentDirectory(new File("D:\\"));
	}
	
	private void sendEmail() {
		MessageVo vo = new MessageVo();
		vo.setUserList(userList);
		vo.setContent(msgEdit.getText());
		vo.setSenderAddr(senderText.getText());
		vo.setSubject(subjectText.getText());
		vo.setContentType(contentType);
		if(SendMail.send(vo, acct)) {
			JOptionPane.showMessageDialog(this, "Send successfully!");
		}else {
			JOptionPane.showMessageDialog(this, "Send failed!");
		}
	}

	private void importUserFile() {
		JFileChooser chooser = new JFileChooser();
		FileNameExtensionFilter filter = new FileNameExtensionFilter(
				"Text files", "txt");
		chooser.setFileFilter(filter);
		int result = chooser.showOpenDialog(this);
		if (result == JFileChooser.APPROVE_OPTION) {
			File tmp = chooser.getSelectedFile();
			if(tmp != null && (toFile == null || (toFile != null && !toFile.equals(tmp)))) {
				toFile = tmp;
				userList = new TextFileProcessor().process(toFile);
				if(userList != null) {
					System.out.println(userList.toString());
				}
				toText.setText(toFile.getPath());
			}			
		}
	}

	private void loadDocument() {		
		int result = chooser.showOpenDialog(this);
		if (result == JFileChooser.APPROVE_OPTION) {
			File doc = chooser.getSelectedFile();
			StringBuilder builder = new StringBuilder();
			try {
				FileInputStream fis = new FileInputStream(doc);
				BufferedReader br = new BufferedReader(new InputStreamReader(
						fis));
				while (br.ready()) {
					builder.append(br.readLine()).append("\n");
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(doc.getName().toLowerCase().endsWith(".rtf")) {
			  msgEdit.setContentType("text/rtf");
			  if(msgTab.getTabCount() > 1) {
			    msgTab.removeTabAt(1);
			  }
			  contentType="text/rtf";
			}else {
			  msgEdit.setContentType("text/plain");
			  msgTab.addTab("Preview", previewScroll);
			  contentType="text/html";
			}
			msgEdit.setText(builder.toString());
			msgPreview.setText(builder.toString());
			
		}
	}

	private void tabChange() {
		if (msgTab.getSelectedIndex() == 1) {
			msgPreview.setText(msgEdit.getText());
		}
	}

	public static void main(String[] args) {
		
//		try {
//      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//      MailEditor editor = new MailEditor();    
//      SwingUtilities.updateComponentTreeUI(editor);
//      editor.setVisible(true);
//    } catch (ClassNotFoundException e) {
//      e.printStackTrace();
//    } catch (InstantiationException e) {
//      e.printStackTrace();
//    } catch (IllegalAccessException e) {
//      e.printStackTrace();
//    } catch (UnsupportedLookAndFeelException e) {
//      e.printStackTrace();
//    }
    
	}
}
